const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'

//获取当前用户的信息
router.post('/getCurrentUserInfo', async (req, res) => {
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select * from user where username = ?'
    db.base(sql, result.username, response => {
        let data = []
        let property = ['用户名', '邮箱', '真实姓名', '职位']


        if (response.length > 0) {
            if (response[0].role_id === null) {
                let val = [ response[0].username, response[0].email, response[0].true_name, '无' ]
                for (let i = 0; i < 4; i++) {
                    let obj = new Object()
                    obj.property = property[i]
                    obj.val = val[i]
                    data.push(obj)
                    // console.log(obj)

                }
                res.json({data})

            }
            else {
                let sql = 'select * from user_role where username = ?'
                db.base(sql, result.username, response => {
                    console.log(response)
                    let val = [ response[0].username, response[0].email, response[0].true_name, response[0].roleName ]
                    console.log(val)
                    for (let i = 0; i < 4; i++) {
                        let obj = new Object()
                        obj.property = property[i]
                        obj.val = val[i]
                        data.push(obj)
                        console.log(obj)
                    }
                    console.log('data=',data)
                    res.json({data})

                })

            }




        }
        else {
            res.json({
                'code': 500,
                'result': 'false',
                'type': 'database_error',
                'content': '服务器数据库出错'
            })
        }
    })
})

module.exports = router
